﻿using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;

namespace Shot.Session
{
    /// <summary>
    /// Implements a file based session manager.
    /// </summary>
    public class SessionManager : ISessionManager
    {
        /// <summary>
        /// App instance
        /// </summary>
        public AppInstance Instance { get; set; }

        /// <summary>
        /// Session key
        /// </summary>
        public string SessionKey { get; set; }

        /// <summary>
        /// Path to JSON file for the session data
        /// </summary>
        public string SessionPath
        {
            get
            {
                return string.Format("Sessions/{0}.json", SessionKey);
            }
        }

        /// <summary>
        /// Session data
        /// </summary>
        private Dictionary<string, object> Data { get; set; }

        /// <summary>
        /// Initialize the session manager
        /// </summary>
        public SessionManager()
        {
            Data = new Dictionary<string, object>();
        }

        /// <summary>
        /// Get a session value
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public object Get(string key)
        {
            Load();
            return Data.ContainsKey(key) ? Data[key] : null;
        }

        /// <summary>
        /// Set a session value
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void Set(string key, object value)
        {
            Load();
            Data[key] = value;
            Save();
        }

        private void Load()
        {
            if (!File.Exists(SessionPath))
            {
                Save();
                return;
            }

            var contents = File.ReadAllText(SessionPath);

            Data = JsonConvert.DeserializeObject<Dictionary<string, object>>(contents) ??
                   new Dictionary<string, object>();
        }

        private void Save()
        {
            var directory = (new FileInfo(SessionPath)).Directory;
            if (directory != null && !directory.Exists) directory.Create();

            File.WriteAllText(SessionPath, JsonConvert.SerializeObject(Data));
        }
    }
}
